﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Plugins;
using WorkFlowCore.UserSelectors;
using WorkFlowCore.IRepositories;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using WorkFlowCore.Common.Tracers;

namespace WorkFlowCore.Framework.UserSelectors
{
    [UserSelector("默认成员选择器")]
   
    [PluginDescription("参数：users=[url,用户字典] 如果传url，接收 post 请求，传参 {SelectionId:string selections 中的Id,Expression:string 表达式,WorkTask:object 当前流程实例,CurrentStep:object 当前审批步骤 }，不传时，默认构造创建人id返回。返回格式参考 【用户数组】")]
    [PluginDescription("用户数组：[{\"Id\":\"\",Name:\"\"}]")]
    [PluginDescription("用户字典：{\"SelectionId\":[{Id:\"\",Name:\"\"}]} SelectionId 值为 selections 中的Id")]
    [PluginDescription("重要说明：这里\"创建人\"传参中的  SelectionId 实际为 流程创建人用户id")]
    public class DefaultUserSelector : IUserSelector,IDefaultUserSelector, IConfigurable, IServiceResolvable
    {
        ConfigureContext configureContext;
        public Task Configure(ConfigureContext configureContext)
        {
            this.configureContext = configureContext;
            return Task.CompletedTask;
        }

        public List<string> GetDefaultSelectionIds()
        {
            return new List<string>() { "creator" };
        }

        public List<Selection> GetSelections()
        {
            using (var activity = WorkflowActivitySource.Source?.StartActivity("DefaultUserSelector.GetSelections"))
            {
                return new List<Selection>()
                {
                    new Selection{ Id="creator", Name="创建人"},
                };
            }
            
        }

        public List<User> GetUsers(SelectorInput input)
        {
            using (var activity = WorkflowActivitySource.Source?.StartActivity("DefaultUserSelector.GetUsers"))
            {
                activity?.AddTag("SelectionId", input.SelectionId);
                var result = new List<User>();
                try
                {
                    switch (input.SelectionId)
                    {
                        case "creator":
                        default:
                            var usersParemeter = configureContext.Parameters.GetOrDefault("users") ?? "";
                            if (usersParemeter.IsNullOrWhiteSpace())
                            {
                                var user = UserList.GetUserById(input.WorkTask?.CreatedUserId);
                                result.Add(new User { Id = input.WorkTask.CreatedUserId, Name = user?.Name });
                            }
                            else
                            {
                                //这里默认已创建人id去查创建人
                                var copyInput = JObject.Parse(JsonConvert.SerializeObject(input));
                                copyInput["SelectionId"] = input.WorkTask?.CreatedUserId;
                                if (usersParemeter.StartsWith("http"))
                                {
                                    var url = usersParemeter;
                                    if (IsServerAvailable(url))
                                    {
                                        var httpClient = new HttpClient();
                                        httpClient.Timeout = TimeSpan.FromSeconds(3);
                                        var resp = httpClient.PostAsync(url, new StringContent(copyInput.ToString(), Encoding.UTF8, "application/json")).Result;
                                        var data = resp.Content.ReadAsStringAsync().Result;
                                        return JsonConvert.DeserializeObject<List<User>>(data);
                                    }
                                }
                                else
                                {
                                    var jObject = JObject.Parse(usersParemeter);
                                    return JsonConvert.DeserializeObject<List<User>>(jObject[input.WorkTask?.CreatedUserId].ToString());
                                }
                            }


                            break;
                    }
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    Console.Error.WriteLine(ex.ToString());
                }
                return result;
            }


           
        }

        public void InitServiceProvider(IServiceProvider ServiceProvider)
        {
        }

        private bool IsServerAvailable(string url)
        {
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "HEAD";               //设置提交方式可以为＂ｇｅｔ＂，＂ｈｅａｄ＂等
                myRequest.Timeout = 300;              //设置网页响应时间长度
                myRequest.AllowAutoRedirect = false;//是否允许自动重定向
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                return (myResponse.StatusCode == HttpStatusCode.OK);//返回响应的状态
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
